<?php

namespace App\Http\Controllers\Admin;

use App\Model\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    //用户登录页面
    public function login(){
        return view('admin.login');
    }
    //用户登录执行
    public function doLogin(Request $request){
        $input=$request->except('_token');
        //表单验证
        $rule=[
            'username'=>'required|between:4,18',
            'password'=>'required|between:4,18'
        ];
        $msg=[
            'username.required'=>'用户名不能为空',
            'password.required'=>'密码不能为空',
            'username.between'=>'用户名长度在4-18位',
            'password.between'=>'密码长度在4-18位',
        ];
        $validator=Validator::make($input,$rule,$msg);
        if($validator->fails()){
            return redirect('admin/login')
                ->withErrors($validator)
                ->withInput();
        }
        $user=User::where('username',$input['username'])->first();
        if(!$user){
            return redirect('admin/login')->with('errors','用户名错误');
        }
        if($input['password']!=$user->password){
            return redirect('admin/login')->with('errors','密码错误');
        }
        //保存用户信息到session
        session()->put('user',$user);
        //跳转到后台首页
        return redirect('admin/index');
    }
    //后台首页
    public function index(){
        return view('admin.index');
    }
    //后台欢迎页
    public function welcome(){
        return view('admin.welcome');
    }
    //后台退出
    public function logout(){
        //清空session
        session()->flush();
        //跳转到登录页面
        return redirect('admin/login');
    }
}
